﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace DCT.CodeBox.LightLog.Codes.Formatter
{
    public class ObjectFormatter : KeyValueLogStringFormatter, ILogStringFormatter
    {
        public string Render(object log)
        {
            if (log == null) {
                return null;
            }
            List<string> logs = new List<string>();

            Type type = log.GetType();
            var properties = GetPropertyInfos(type);
            if (properties == null)
            {
                logs.Add(log.ToString());
            }
            else
            {
                foreach (var property in properties)
                {
                    string name = property.Name;
                    object objVal = property.GetValue(log, null);
                    string val = "";
                    if (objVal != null)
                    {
                        val = objVal.ToString();
                    }
                    logs.Add(string.Format(this.Formatter, name, val));
                }
            }

            return string.Join(this.Split, logs.ToArray());
        }

        private static Dictionary<Type, PropertyInfo[]> propsCache = new Dictionary<Type, PropertyInfo[]>();

        private static PropertyInfo[] GetPropertyInfos(Type type) {
            if (type == null) {
                return null;
            }
            if (!propsCache.ContainsKey(type)) {
                propsCache[type] = type.GetProperties();
            }
            return propsCache[type];
        }
    }
}
